import { createRouter, createWebHistory } from "vue-router";
import type { RouteRecordRaw } from "vue-router";
import remainingRouter from "./modules/remaining";
// 获取所有的菜单路由
const modules = import.meta.glob<{ default: RouteRecordRaw[] }>(
  ["./modules/**/*.ts", "!./modules/**/remaining.ts"],
  { eager: true }
);

const routes: RouteRecordRaw[] = [];
Object.keys(modules).forEach((key) => {
  routes.push(...modules[key].default);
});

// 合并路由
const routeses: RouteRecordRaw[] = [...routes, ...remainingRouter];

// 修改路由配置
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routeses, // 直接合并所有路由
  // 开启严格模式
  strict: true,
  // 滚动行为控制
  scrollBehavior(to, from, savedPosition) {
    return new Promise((resolve) => {
      if (savedPosition) {
        return savedPosition;
      } else {
        if (from.meta.saveSrollTop) {
          const top: number = document.documentElement.scrollTop || document.body.scrollTop;
          resolve({ left: 0, top });
        }
      }
    });
  },
});

// 修改路由守卫逻辑
router.beforeEach(async (to, from, next) => {
  // console.log("beforeEach", to.fullPath);
  const token = localStorage.getItem("token");
  const whiteList = ["login", "404"];
  // 访问白名单页面
  if (whiteList.includes(to.name as string) || whiteList.includes(to.path)) {
    if (token && to.name === "login") {
      // 已登录访问登录页，跳首页
      next({ path: "/" });
    } else {
      next();
    }
    return;
  }
  // 非白名单，校验 token
  if (!token) {
    return next({ name: "login" });
  }
  // 放行
  next();
});

export default router;
